﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
using Green.FastInvoker;
using Green.Utility;

namespace Green.AgileMapper
{
    public class ObjectMappingRule : IMappingRule, IXmlConfigLoad
    {
        public string FromPoperty
        { get; private set; }

        public string ToPoperty
        { get; private set; }

        public ObjectMappingRule(string fromProperty, string toPropety)
        {
            this.FromPoperty = fromProperty;
            this.ToPoperty = toPropety;
        }

        public ObjectMappingRule()
        {
        }
       

        #region IMappingRule 成员
        /// <summary>
        /// 根据 To得到From
        /// </summary>
        /// <param name="from"></param>
        /// <param name="to"></param>
        public virtual void WarpFrom(object from, object to)
        {
            var toObject = PropertyAccessor.Get(to, ToPoperty);           
            var objectMapper = new DefaultObjectMapper(new AttributeMappingConfigurator());            
            var fromObject = objectMapper.Warp(  PropertyAccessor.GetPropertyType(from, FromPoperty), toObject);
            PropertyAccessor.Set(from, this.FromPoperty, fromObject);
        }


       

        /// <summary>
        /// 根据From得到To
        /// </summary>
        /// <param name="from"></param>
        /// <param name="to"></param>
        public virtual void WarpTo(object from, object to)
        {
            var fromObject = PropertyAccessor.Get(from, this.FromPoperty);
            var objectMapper = new DefaultObjectMapper(new AttributeMappingConfigurator());
            object toObject = PropertyAccessor.Get(to, this.ToPoperty);
           
            var toPropertyType = toObject == null
                                     ? PropertyAccessor.GetPropertyType(to, this.ToPoperty)
                                     : toObject.GetType();
            if (toObject==null)
            {
                toObject = Activator.CreateInstance(toPropertyType);
            }
            objectMapper.Warp(toPropertyType, fromObject, toObject);
            PropertyAccessor.Set(to, this.ToPoperty, toObject);
        }

        #endregion

        #region IXmlConfigLoad 成员

        public void LoadXmlConfig(Dictionary<string, object> propertys)
        {
            this.FromPoperty = propertys.TryGetValue<string, string>("FromPoperty", string.Empty);
            this.ToPoperty = propertys.TryGetValue<string, string>("ToPoperty", string.Empty);
            //this.IsConvertTo = propertys.TryGetValue<string, bool>("IsConvertTo", true);
            //this.IsConvertFrom = propertys.TryGetValue("IsConvertFrom", true);
        }

        #endregion
    }
}
